#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>

#define BUFSIZE 1000

void error_handling(char *message) {
    fputs(message, stderr);
    fputc('\n', stderr);
    exit(1);
}

int main(int argc, char *argv[]) {
    int server_sock;
    int connfd;
    // 1.socket
    if ((server_sock = socket(PF_INET, SOCK_STREAM, 0)) == -1)
        error_handling("socket() error");
  
    char buf[BUFSIZE];

    struct sockaddr_in server_addr;
    struct sockaddr_in client_addr;
    
    if (argc != 2) {
        printf("Usage : %s <port>\n", argv[0]); 
        exit(1);
    }

    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    server_addr.sin_port = htons(atoi(argv[1]));

    // 2.bind
    if (bind(server_sock, (struct sockaddr*)&server_addr, sizeof(server_addr)) == -1) 
        error_handling("bind() error");
    
    // 3.listen
    if (listen(server_sock, 5) == -1)
        error_handling("listen() error");
    
    // 4.accept
    socklen_t client_addr_size = sizeof(client_addr);
    connfd = accept(server_sock, (struct sockaddr*)&client_addr, &client_addr_size);
    if (connfd == -1)
        error_handling("accept() error");

    // 5.write 
    FILE *fp = fopen("summary.txt", "rb");
    // 分多次将文件fp写入connfd中
    while (1) {
        int read_len = fread((void *)buf, 1, BUFSIZE, fp);
        int len = BUFSIZE < read_len ? BUFSIZE : read_len;
        write(connfd, buf, len);
        if (read_len < BUFSIZE) 
            break;
    }
    // 6.发送半关闭信息, 只接收不写入
    shutdown(connfd, SHUT_WR);
    read(connfd, buf, BUFSIZE);
    printf("message from client: %s \n", buf);
    fclose(fp);
    close(server_sock); close(connfd);
    return 0;
}